<?php
error_reporting(E_ALL ^E_NOTICE);
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_MAMBOTS->registerFunction( 'onPayProsessStart', 'jeProcessWorldPayStart' );
$_MAMBOTS->registerFunction( 'onPayProsessFinish', 'jeProcessWorldPayFinish' );
function jeProcessWorldPayFinish()
{
    Global $my, $database, $mosConfig_live_site;

    $processor = mosGetParam( $_REQUEST, 'processor'); 
    if($processor != '.worldpay') return false;

    $order['id']         = mosGetParam( $_REQUEST, 'sub_id');
    $order['gateway']    = $processor;
    $order['gateway_id'] = mosGetParam( $_REQUEST, 'transaction');
    $order['price']      = mosGetParam( $_REQUEST, 'amount');
    $order['user']       = mosGetParam( $_REQUEST, 'user', mosGetParam( $_REQUEST, 'MC_user'));
    
    mosGetParam( $_REQUEST, 'transStatus') == 'Y' ? 
        $order['pay'] = 'success' : $order['pay'] = 'fail';
    
    return $order;
}

function jeProcessWorldPayStart( $params )
{
    Global $my, $database, $mosConfig_live_site, $mosConfig_absolute_path, $JCS_ORDER_COMPLETE, $JCS_ORDER_INCOMPLETE;
    
    if($params['processor'] != '.worldpay') return;

    $query = "SELECT id"
    . "\n FROM #__mambots"
    . "\n WHERE element = 'joomlaequipment.payprocessor{$params[processor]}'"
    . "\n AND folder = 'system'"
    ;
    $database->setQuery( $query );
    $id     = $database->loadResult();
    $mambot = new mosMambot( $database );
    $mambot->load( $id );
    $botParams = new mosParameters( $mambot->params );
    
    $param['amount']    = floatval($params['order_amount']);
    $param['instId']    = $botParams->def('merchant');
    $param['cartId']    = $params['order_id'];
    $param['MC_user']   = $my->id;
    $param['desc']      = strval($params['order_title']);
    $param['currency']  = $botParams->def('currency');
    $param['email']     = $my->email;
    $param['currency']  = $botParams->def('currency');
    $param['address']   = $botParams->def('address');
    $param['country']   = $botParams->def('country');
    
    if($botParams->def('testMode')) $param['testMode'] = urlencode($botParams->def('testMode'));

    if(!$param['amount'] || !$param['instId'])
    {
        echo "<P><h1>Error Payment Processing: some of the params passed are empty</h1></P>";
        return;
    }
    $url = 'https://select.worldpay.com/wcc/purchase?'.jpArray2Url($param);
    //echo str_replace("&", "<BR>", $url);
    header("location: $url");
}

if(!defined('JP_IMPLODE'))
{
    define('JP_IMPLODE', 1);
    function jpArray2Url($param)
    {
        foreach($param AS $k => $v)
        {
            $out[] = "$k=$v";
        }
        return implode('&', $out );
    }
}



?>
